using System.Security.Principal;
using AdminSecurity.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

public class UserNavigationRequirement(IServiceProvider serviceProvider) : AuthorizationHandler<UserNavigationRequirement>, IAuthorizationRequirement
{
    private readonly ISecutityAdminService _securityAdminService = serviceProvider.GetRequiredService<ISecutityAdminService>();
    private readonly IHttpContextAccessor _httpContextAccessor = serviceProvider.GetRequiredService<IHttpContextAccessor>();
    private readonly IConfiguration _configuration = serviceProvider.GetRequiredService<IConfiguration>();

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserNavigationRequirement requirement)
    {
        // 检查用户是否已登录
        if (context.User.Identity?.IsAuthenticated != true)
        {
            return Task.CompletedTask;
        }

        // 检查当前请求是否包含 [UserNavigation] 特性
        var endpoint = _httpContextAccessor.HttpContext?.GetEndpoint();
        var userNavigationAttribute = endpoint?.Metadata.GetMetadata<UserNavigationAttribute>();

        if (userNavigationAttribute == null)
        {
            // 如果没有 [UserNavigation] 特性，直接通过
            context.Succeed(requirement);
            return Task.CompletedTask;
        }

        // 如果用户是管理员，直接通过
        if (context.User.IsInRole("Administrator"))
        {
            context.Succeed(requirement);
            return Task.CompletedTask;
        }

        // 获取导航权限相关信息
        var menuName = userNavigationAttribute.UserNavigation_Name;
        var userName = context.User.Identity.Name;
        var appId = "main"; // 这里可以根据需要动态获取应用程序 ID

        // 验证用户是否有导航权限
        if (!string.IsNullOrEmpty(userName) && _securityAdminService.GetMenusByUsernaem(userName, menuName, appId))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}
 
